import { useEffect, useState, useRef } from "react";
import { Avatar } from "antd";
import { UserOutlined, DownOutlined } from "@ant-design/icons";
import DropdownMenu from "./DropdownMenu";
import NavPopover from "./NavPopover";
import styles from "./HeaderCom.module.css";
import logo from "./images/logo.png";
import logoGif from "./images/logo.gif";
import avatar from "./images/avatar.png";
import LoginModal from "../login/LoginModal";
import SubMenu from "../../../../components/commonSubMenu/SubMenu";
import { useUserStore } from "../../../../store/userStore";

const navs = [
  {
    text: "视频",
    searchPlaceholder: "搜索海量视频模板源文件",
    images: [
      { src: "https://picsum.photos/200/300", text: "4K视频" },
      { src: "https://picsum.photos/200/300", text: "高清视频" },
      { src: "https://picsum.photos/200/300", text: "特效视频" },
    ],
    categories: [
      {
        title: "视频格式",
        items: ["4K视频", "1080P视频", "720P视频", "高清视频", "标清视频"],
      },
      {
        title: "视频类型",
        items: ["实拍视频", "动画视频", "特效视频", "航拍视频", "慢动作视频"],
      },
      {
        title: "应用场景",
        items: ["商业广告", "产品展示", "企业宣传", "活动记录", "教育培训"],
      },
    ],
  },
  {
    text: "实拍",
    searchPlaceholder: "搜索实拍视频素材",
    images: [
      { src: "https://picsum.photos/200/300", text: "自然实拍" },
      { src: "https://picsum.photos/200/300", text: "人物实拍" },
      { src: "https://picsum.photos/200/300", text: "城市实拍" },
    ],
    categories: [
      {
        title: "自然风光",
        items: ["山水风景", "日落晚霞", "海洋风光", "森林草原", "雪景冰川"],
      },
      {
        title: "城市生活",
        items: ["城市街景", "建筑景观", "交通设施", "商业场所", "公共空间"],
      },
      {
        title: "人物活动",
        items: ["商务办公", "生活日常", "运动健身", "休闲娱乐", "社交活动"],
      },
    ],
  },
  {
    text: "设计模板",
    searchPlaceholder: "搜索设计模板素材",
    images: [
      { src: "https://picsum.photos/200/300", text: "商业设计" },
      { src: "https://picsum.photos/200/300", text: "海报设计" },
      { src: "https://picsum.photos/200/300", text: "UI设计" },
    ],
    categories: [
      {
        title: "平面设计",
        items: ["海报设计", "名片设计", "包装设计", "宣传册设计", "品牌设计"],
      },
      {
        title: "UI设计",
        items: ["移动应用", "网页设计", "小程序设计", "图标设计", "banner设计"],
      },
      {
        title: "广告设计",
        items: ["户外广告", "社交广告", "展览设计", "活动主视觉", "品牌形象"],
      },
    ],
  },
  {
    text: "PPT",
    searchPlaceholder: "搜索PPT模板",
    images: [
      { src: "https://picsum.photos/200/300", text: "商务PPT" },
      { src: "https://picsum.photos/200/300", text: "教育PPT" },
      { src: "https://picsum.photos/200/300", text: "创意PPT" },
    ],
    categories: [
      {
        title: "商务PPT",
        items: ["工作汇报", "商业计划", "企业介绍", "数据分析", "项目展示"],
      },
      {
        title: "教育PPT",
        items: ["课件模板", "论文答辩", "教学课件", "培训教材", "考试课件"],
      },
      {
        title: "创意PPT",
        items: ["图表模板", "版式设计", "背景模板", "动画效果", "图形素材"],
      },
    ],
  },
  {
    text: "摄影",
    searchPlaceholder: "搜索摄影作品",
    images: [
      { src: "https://picsum.photos/200/300", text: "风光摄影" },
      { src: "https://picsum.photos/200/300", text: "人像摄影" },
      { src: "https://picsum.photos/200/300", text: "商业摄影" },
    ],
    categories: [
      {
        title: "风光摄影",
        items: ["自然风光", "城市风光", "建筑摄影", "人文风光", "黑白风光"],
      },
      {
        title: "人像摄影",
        items: ["写真摄影", "商业人像", "艺术人像", "儿童摄影", "婚纱摄影"],
      },
      {
        title: "商业摄影",
        items: ["产品摄影", "美食摄影", "活动摄影", "广告摄影", "时尚摄影"],
      },
    ],
  },
  {
    text: "人像",
    searchPlaceholder: "搜索人像素材",
    images: [
      { src: "https://picsum.photos/200/300", text: "商务人像" },
      { src: "https://picsum.photos/200/300", text: "生活人像" },
      { src: "https://picsum.photos/200/300", text: "艺术人像" },
    ],
    categories: [
      {
        title: "商务人像",
        items: ["职场精英", "团队合作", "会议场景", "办公场景", "商务洽谈"],
      },
      {
        title: "生活人像",
        items: ["日常生活", "家庭场景", "休闲娱乐", "运动健身", "社交场景"],
      },
      {
        title: "艺术人像",
        items: ["写真艺术", "黑白人像", "创意人像", "时尚人像", "复古人像"],
      },
    ],
  },
  {
    text: "素材导航",
    searchPlaceholder: "搜索素材资源",
    images: [
      { src: "https://picsum.photos/200/300", text: "热门素材" },
      { src: "https://picsum.photos/200/300", text: "最新上传" },
      { src: "https://picsum.photos/200/300", text: "推荐素材" },
    ],
    categories: [
      {
        title: "素材分类",
        items: ["图片素材", "视频素材", "音频素材", "字体素材", "图标素材"],
      },
      {
        title: "应用场景",
        items: ["电商设计", "自媒体", "广告营销", "教育培训", "企业宣传"],
      },
      {
        title: "创作工具",
        items: ["PS教程", "PR教程", "AE教程", "AI教程", "C4D教程"],
      },
    ],
  },
  {
    text: "企业站",
    searchPlaceholder: "搜索企业相关素材",
    images: [
      { src: "https://picsum.photos/200/300", text: "企业形象" },
      { src: "https://picsum.photos/200/300", text: "产品展示" },
      { src: "https://picsum.photos/200/300", text: "团队风采" },
    ],
    categories: [
      {
        title: "企业形象",
        items: ["logo设计", "VI设计", "宣传片制作", "广告设计", "品牌策划"],
      },
      {
        title: "营销物料",
        items: ["产品目录", "宣传册设计", "海报设计", "包装设计", "展会设计"],
      },
      {
        title: "办公文化",
        items: ["工作照片", "团建活动", "会议记录", "企业文化", "员工风采"],
      },
    ],
  },
  {
    text: "政务图库",
    searchPlaceholder: "搜索政务相关素材",
    images: [
      { src: "https://picsum.photos/200/300", text: "政务新闻" },
      { src: "https://picsum.photos/200/300", text: "城市建设" },
      { src: "https://picsum.photos/200/300", text: "民生服务" },
    ],
    categories: [
      {
        title: "政务新闻",
        items: ["会议活动", "领导视察", "重大事件", "工作部署", "成果展示"],
      },
      {
        title: "城市建设",
        items: ["基础设施", "民生工程", "环境保护", "城市规划", "重点项目"],
      },
      {
        title: "公共服务",
        items: ["便民服务", "政策宣传", "安全教育", "文化活动", "社区服务"],
      },
    ],
  },
];

function HeaderCom() {
  const { isLoggedIn, userInfo, logout } = useUserStore();
  const [showLogin, setShowLogin] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const [hoveredButton, setHoveredButton] = useState<string | null>(null);
  const [isDropdownHovered, setIsDropdownHovered] = useState(false);
  const [hoveredNav, setHoveredNav] = useState<string | null>(null);
  const [popoverPosition, setPopoverPosition] = useState({ x: 0, y: 0 });
  const closeTimerRef = useRef<number | null>(null);
  const dropdownTimerRef = useRef<number | null>(null);
  const buttonRefs = {
    category: useRef<HTMLButtonElement>(null),
    more: useRef<HTMLButtonElement>(null),
  };
  // const headerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => {
      // 修改为滚动超过50px才触发变化，避免过于敏感
      setIsScrolled(window.scrollY > 50);
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);
  const handleNavMouseEnter = (
    event: React.MouseEvent<HTMLLIElement>,
    nav: string
  ) => {
    if (closeTimerRef.current) {
      window.clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
    const rect = event.currentTarget.getBoundingClientRect();
    setPopoverPosition({
      x: rect.left + rect.width / 2,
      y: rect.bottom,
    });
    setHoveredNav(nav);
  };
  // 处理导航鼠标离开事件
  const handleNavMouseLeave = () => {
    // 设置定时器，200毫秒后执行
    closeTimerRef.current = window.setTimeout(() => {
      // 如果没有悬停在下拉菜单上，则设置悬停的导航为null
      if (!isDropdownHovered) {
        setHoveredNav(null);
      }
    }, 200);
  };
  // 当鼠标进入按钮时，清除定时器，并设置当前悬停的按钮类型
  const handleButtonMouseEnter = (buttonType: string) => {
    // 如果当前有定时器，清除定时器，并将定时器引用置为null
    if (dropdownTimerRef.current) {
      window.clearTimeout(dropdownTimerRef.current);
      dropdownTimerRef.current = null;
    }
    // 设置当前悬停的按钮类型
    setHoveredButton(buttonType);
  };
  const handleButtonMouseLeave = () => {
    dropdownTimerRef.current = window.setTimeout(() => {
      if (!isDropdownHovered) {
        setHoveredButton(null);
      }
    }, 200);
  };
  const handleDropdownMouseEnter = () => {
    if (dropdownTimerRef.current) {
      window.clearTimeout(dropdownTimerRef.current);
      dropdownTimerRef.current = null;
    }
    setIsDropdownHovered(true);
  };
  const handleDropdownMouseLeave = () => {
    setIsDropdownHovered(false);
    dropdownTimerRef.current = window.setTimeout(() => {
      setHoveredButton(null);
    }, 200);
  };
  const handlePopoverMouseEnter = () => {
    if (closeTimerRef.current) {
      window.clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
    setIsDropdownHovered(true);
  };
  const handlePopoverMouseLeave = () => {
    setIsDropdownHovered(false);
    setHoveredNav(null);
  };

  return (
    <div
      className={`${styles.header} ${isScrolled ? `${styles.headerSticky} ${styles.headerScrolled}` : ""
        }`}
    >
      <div className={styles.left}>
        <img
          src={isScrolled ? logoGif : logo}
          alt="logo"
          className={`${styles.logo} ${isScrolled ? styles.logoGif : ""}`}
        />

        {/* 导航链接 - 滚动时隐藏 */}
        <ul className={styles.navs}>
          {navs.map((item) => (
            <li
              key={item.text}
              onMouseEnter={(e) => handleNavMouseEnter(e, item.text)}
              onMouseLeave={handleNavMouseLeave}
            >
              {item.text}
            </li>
          ))}
        </ul>

        <NavPopover
          visible={!!hoveredNav}
          position={popoverPosition}
          data={
            navs.find((item) => item.text === hoveredNav) || {
              searchPlaceholder: "",
              images: [],
              categories: [],
            }
          }
          onMouseEnter={handlePopoverMouseEnter}
          onMouseLeave={handlePopoverMouseLeave}
        />

        {isScrolled && (
          <div className={styles.actionButtons}>
            <button className={styles.actionBtn}>首页</button>
            <button
              ref={buttonRefs.category}
              className={styles.actionBtn}
              onMouseEnter={() => handleButtonMouseEnter("category")}
              onMouseLeave={handleButtonMouseLeave}
            >
              全部分类
              <DownOutlined className={styles.arrowIcon} />
            </button>
            <button
              ref={buttonRefs.more}
              className={styles.actionBtn}
              onMouseEnter={() => handleButtonMouseEnter("more")}
              onMouseLeave={handleButtonMouseLeave}
            >
              更多
              <DownOutlined className={styles.arrowIcon} />
            </button>
            <DropdownMenu
              position={buttonRefs[hoveredButton as keyof typeof buttonRefs]?.current?.getBoundingClientRect() ?? null}
              visible={!!hoveredButton}
              content={
                hoveredButton === "category" ? (
                  <div
                    onMouseEnter={handleDropdownMouseEnter}
                    onMouseLeave={handleDropdownMouseLeave}
                  >
                    <SubMenu />
                  </div>
                ) : (
                  <div
                    onMouseEnter={handleDropdownMouseEnter}
                    onMouseLeave={handleDropdownMouseLeave}
                  >
                    <div key="1" className={styles.dropdownItem}>个人中心</div>
                    <div key="2" className={styles.dropdownItem}>帮助文档</div>
                    <div key="3" className={styles.dropdownItem}>问题反馈</div>
                  </div>
                )
              }
            />
          </div>
        )}
        {/* 搜索框 - 滚动时显示 */}
        {isScrolled && (
          <div className={styles.searchBox}>
            <select className={styles.select}>
              <option>全部分类</option>
              {navs.map((item) => (
                <option key={item.text}>{item.text}</option>
              ))}
            </select>
            <input
              className={styles.input}
              placeholder="百万视频上新，点击搜索查看"
            />
            <button className={styles.searchBtn} >搜索</button>
          </div>
        )}
      </div>

      <div className={styles.right}>
        <button className={styles.vipBtn}>企业VIP授权</button>
        <button className={styles.vipBtn}>个人VIP</button>
        {isLoggedIn ? (
          <>
            <Avatar src={avatar} icon={<UserOutlined />} />
            <span className={styles.phoneNumber}>{userInfo?.phone}</span>
            <button className={styles.logoutBtn} onClick={logout}>
              退出
            </button>
          </>
        ) : (
          <button className={styles.loginBtn} onClick={() => setShowLogin(true)}>
            登录/注册
          </button>
        )}
        {showLogin && (
          <LoginModal visible={showLogin} onClose={() => setShowLogin(false)} />
        )}
      </div>
    </div>
  );
}

export default HeaderCom;
